package org.bhf.providers.router;

import org.bhf.service.URLRouter.RouteMatch;

import java.util.Map;
import java.util.LinkedHashMap;

/**
 * Cache URI to Route Matches. This class is not thread safe.
 */
final class RouteCache
{
    private static final int MAX_ENTRIES = 50;

    private final Map<RouteRequest,RouteMatch> forwardCache = new LinkedHashMap<RouteRequest,RouteMatch>( 50, 0.75F, true )
    {
        public static final long serialVersionUID = 1L;
        
        protected boolean removeEldestEntry( final Map.Entry<RouteRequest,RouteMatch> eldest )
        {
            return size() > MAX_ENTRIES;
        }
    };

    //
    // Foward caching
    //

    RouteMatch  route( final String extenalURI, final String hostName )
    {
        return forwardCache.get( new RouteRequest( extenalURI, hostName ) );
    }

    void        addRoute( final String extenalURI, final String hostName, final RouteMatch route )
    {
        forwardCache.put( new RouteRequest( extenalURI, hostName ), route );
    }

    static class RouteRequest
    {
        final String extenalURI;
        final String hostName;

        public RouteRequest( final String extenalURI, final String hostName )
        {
            this.extenalURI = extenalURI;
            this.hostName   = hostName;
        }

        public boolean equals( Object o )
        {
            if( this == o ) return true;
            if( o == null || getClass() != o.getClass() ) return false;

            RouteRequest that = (RouteRequest)o;

            return extenalURI.equals( that.extenalURI ) && hostName.equals( that.hostName );
        }

        public int hashCode()
        {
            int result;
            result = extenalURI.hashCode();
            result = 31 * result + hostName.hashCode();
            return result;
        }
    }
}
